package org.projsquirrel;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.*;
import android.util.Log;
import android.view.*;
import android.location.*;

@SuppressWarnings("unused")
public class SurveyActivity extends Activity
{
	private Context localInstance;
    private TableRow tableTime, tableDate, tableZip;
    private TextView textTime, textDate, textZip;
    private int hour, minute, Year, month, day;
    static final int MAP_ACTIVITY = 100;
    static final int TIME_DIALOG_ID = 0;
    static final int DATE_DIALOG_ID = 1;
    static final int EMAIL_DIALOG_ID = 2;
    static final int DELTA_DIALOG_ID = 3;
    static final int THISSITE_DIALOG_ID = 4;
    static final int OTHERSITE_DIALOG_ID = 5;
    static final int SITE_DIALOG_ID = 6;
    
    public LocationManager locationManager;
    private Canvas imagecanvas;
    private Button myButton;
    
    //Your Opinion...
    private TextView tableEmail, tableDeltaSquirrel, tableThisSite, tableOtherSite, tableComments;
    private TextView email, deltaSquirrel, thisSite, otherSite, comments;
    private Button submit;
    
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.survey);
       // TableRow NewRow = new TableRow( localInstance, null); This line breaks stuff. -5 internets
        localInstance = this;
        
        //location manager initialization
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        
        //link all variables to the View
        tableTime = (TableRow)findViewById(R.id.table_time);
        tableDate = (TableRow)findViewById(R.id.table_date);
        tableZip = (TableRow)findViewById(R.id.table_zip);
        textTime = (TextView)findViewById(R.id.text_time);
        textDate = (TextView)findViewById(R.id.text_date);
        textZip = (TextView)findViewById(R.id.text_zip);
       
        tableEmail = (TextView)findViewById(R.id.answer_email);
        tableDeltaSquirrel = (TextView)findViewById(R.id.answer_deltaSquirrel);
        tableThisSite = (TextView)findViewById(R.id.answer_thisSite);
        tableOtherSite = (TextView)findViewById(R.id.answer_otherSite);
        email = (TextView)findViewById(R.id.text_email);
        deltaSquirrel = (TextView)findViewById(R.id.text_deltaSquirrel);
        thisSite = (TextView)findViewById(R.id.text_thisSite);
        otherSite = (TextView)findViewById(R.id.text_otherSite);
        
        submit = (Button)findViewById(R.id.button_submit);
        
        final Calendar c = Calendar.getInstance();
        
        //set the defaults for the time
        hour = c.get(Calendar.HOUR_OF_DAY);
        minute = c.get(Calendar.MINUTE);
        
        //set if its AM or PM
        String amPm;
        if(hour > 11)
        	amPm = "PM";
        else
        	amPm = "AM";
        
        //format the hours
        if(hour > 12)
        	hour -= 12;
        if(hour == 0)
        	hour = 12;
        
        //format the minutes
        String zero;
        if(minute < 10)
        	zero = "0";
        else
        	zero = "";
        
        //set the textTime            
        textTime.setText(hour + ":" + zero + minute + " " + amPm);
        
        //set the defaults for the date
        Year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);
        textDate.setText(month + 1 + "/" + day + "/" + Year);
                
		//set default zip code
        /*
		Location current = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		Geocoder geo = new Geocoder(this,Locale.getDefault());
		List<Address> addresses;
		try {
			addresses = geo.getFromLocation(current.getLatitude(), current.getLongitude(), 1);
			if(addresses != null && addresses.get(0).getPostalCode() != null)
				textZip.setText(addresses.get(0).getPostalCode());
			else
				textZip.setText("Select location from map");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		*/
    
        //set the default for Your Opinion section
         tableDeltaSquirrel.setText("Stayed the Same");
         tableEmail.setText("");
         tableThisSite.setText("No");
         tableOtherSite.setText("No");
      
        //link the On Click Events to the TextViews
        tableTime.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		}); 
        tableDate.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});
        tableZip.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {
				Intent intent = new Intent(localInstance, Map.class);
				startActivityForResult(intent, MAP_ACTIVITY);
			}
		});
 
        tableDeltaSquirrel.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		showDialog(DELTA_DIALOG_ID);
        	}
        });
        
        tableThisSite.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		showDialog(THISSITE_DIALOG_ID);
        	}
        });
        
        tableOtherSite.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		showDialog(OTHERSITE_DIALOG_ID);
        	}
        });
        submit.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		createReport();
        	}
        });
   	}
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
    	if(requestCode == MAP_ACTIVITY && resultCode == RESULT_OK) //the map activity has returned and it supplied a new location
    	{
    		textZip.setText(data.getCharSequenceExtra("zip"));    		
    	}
    }    
    
    
	protected void createReport() 
	{
		//regular expressions to find if a valid email address
    	boolean b = Pattern.matches("[\\w+.-]+@[\\w.]+", tableEmail.getText());
    	if( b) //value matches a valid email address
    	{
    		email.setTextColor(Color.WHITE);
    		Toast.makeText(getApplicationContext(), "Report Submitted", Toast.LENGTH_SHORT).show();
    	}
    	else
    	{
    		email.setTextColor(Color.RED);
    		Toast.makeText(getApplicationContext(), "Email Invalid", Toast.LENGTH_LONG).show();
    		
    	}
	}	

    protected Dialog onCreateDialog(int id)
    {
    	switch(id)
    	{
    	case TIME_DIALOG_ID:
    		return new TimePickerDialog(this,mTimeSetListener, hour, minute, false);
    	case DATE_DIALOG_ID:
    		return new DatePickerDialog(this,mDateSetListener, Year, month, day);
    	case EMAIL_DIALOG_ID:
    		
    		break;
	    case DELTA_DIALOG_ID:
	    	final CharSequence[] delta_items = {"Increased", "Decreased", "Stayed the Same"};
	    	AlertDialog.Builder delta_builder = new AlertDialog.Builder(this);
	    	delta_builder.setTitle("Number has");
	    	delta_builder.setItems(delta_items, new DialogInterface.OnClickListener() {
	    	    public void onClick(DialogInterface dialog, int item) {
	    	        //Toast.makeText(getApplicationContext(), delta_items[item], Toast.LENGTH_SHORT).show();
	    	    	tableDeltaSquirrel.setText(delta_items[item]);
	    	    }
	    	});
	    	AlertDialog delta_alert = delta_builder.create();
	    	return delta_alert;
	    //Alternate Multiple Choice
	    case SITE_DIALOG_ID:
	    	final CharSequence[] site_items = {"This Location", "Other Locations"};
	    	AlertDialog.Builder site_builder = new AlertDialog.Builder(this);
	    	site_builder.setTitle("Have logged for");
	    	site_builder.setMultiChoiceItems(site_items, null, new DialogInterface.OnMultiChoiceClickListener() {
	    	    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
	    	    	//Needs logic to display based on what the site text already is
	    	       // Toast.makeText(getApplicationContext(), site_items[which], Toast.LENGTH_SHORT).show();
	    	    	tableThisSite.setText(site_items[which]);	
	    	    }
	    	});
	    	AlertDialog site_alert = site_builder.create();
	    	return site_alert;
	    	
	    case OTHERSITE_DIALOG_ID:
	    	final CharSequence[] otherSite_items = {"Yes", "No"};
	    	AlertDialog.Builder otherSite_builder = new AlertDialog.Builder(this);
	    	otherSite_builder.setTitle("Logged other locations");
	    	otherSite_builder.setItems(otherSite_items, new DialogInterface.OnClickListener() {
	    	    public void onClick(DialogInterface dialog, int item) {
	    	        //Toast.makeText(getApplicationContext(), delta_items[item], Toast.LENGTH_SHORT).show();
	    	    	tableOtherSite.setText(otherSite_items[item]);
	    	    }
	    	});
	    	AlertDialog otherSite_alert = otherSite_builder.create();
	    	return otherSite_alert;
	    case THISSITE_DIALOG_ID:
	    	final CharSequence[] thisSite_items = {"Yes", "No"};
	    	AlertDialog.Builder thisSite_builder = new AlertDialog.Builder(this);
	    	thisSite_builder.setTitle("Logged this location");
	    	thisSite_builder.setItems(thisSite_items, new DialogInterface.OnClickListener() {
	    	    public void onClick(DialogInterface dialog, int item) {
	    	        //Toast.makeText(getApplicationContext(), delta_items[item], Toast.LENGTH_SHORT).show();
	    	    	tableThisSite.setText(thisSite_items[item]);
	    	    }
	    	});
	    	AlertDialog thisSite_alert = thisSite_builder.create();
	    	return thisSite_alert;
    	}
    	return null;
    }
    
    private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener()
    {		
		public void onTimeSet(TimePicker view, int hourOfDay, int minuteOfHour)
		{
            hour = hourOfDay;
            minute = minuteOfHour;  
            
            //set if its AM or PM
            String amPm;
            if(hour > 11)
            	amPm = "PM";
            else
            	amPm = "AM";
            
            //format the hours
            if(hour > 12)
            	hour -= 12;
            if(hour == 0)
            	hour = 12;
            
            //format the minutes
            String zero;
            if(minute < 10)
            	zero = "0";
            else
            	zero = "";
            
            //set the textTime            
            textTime.setText(hour + ":" + zero + minute + " " + amPm);
		}
	};
	
    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() 
    {
         public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
         {
        	 Year = year;
             month = monthOfYear;
             day = dayOfMonth;
             textDate.setText(month + 1 + "/" + day + "/" + Year);
          }
     };
    
	private void iSawFactory(int id, int height, int width, String question, int drawable) 	
	{
		//this section still needs testing.
//	    LinearLayout pyramidLayout = (LinearLayout) findViewById(R.id.pyramid); //this is the base layout ie survey
//	    View rowView = getLayoutInflater().inflate(R.layout.row, null);
//	    LinearLayout rowLayout = (LinearLayout) rowView.findViewById(R.id.row);
		char[] defaultValue = {'N','O','N','E'};
		char[] questionText = question.toCharArray();
		// TODO Auto-generated method stub
		RelativeLayout survey = (RelativeLayout) findViewById(R.id.widget218);
		LayoutInflater linflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View myView = linflater.inflate(R.layout.survey_element, null);
        
        TextView v = (TextView) myView.findViewById(R.id.Text);
        TextView q = (TextView) myView.findViewById(R.id.question);
        ImageView i = (ImageView) myView.findViewById(R.id.image);
        Button btnExpand = (Button) myView.findViewById(R.id.btnExpand);
        ImageButton btnDwn = (ImageButton) myView.findViewById(R.id.btnDwn);
        ImageButton btnUp = (ImageButton) myView.findViewById(R.id.btnUp);
        
        q.setText(questionText, 0, questionText.length);
        v.setText(defaultValue, 0, defaultValue.length);
        i.setImageResource(drawable);
        
        //there might be an issue with the ID's here during runtime need to look into a better way of doing this.
        v.setId(id*2+id);
        q.setId(id*2*id*2*id*2*id*2 + id);
        i.setId(id*2*id*2 + id);
        btnExpand.setId(id*2*id*2*id*2 + id);
        btnDwn.setId(id*2*id*2*id*2*id*2*id*2 + id);
        btnUp.setId(id*2*id*2*id*2*id*2*id*2*id*2 + id);
        
        btnExpand.setOnClickListener(new View.OnClickListener() {
			
	//		@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
        btnDwn.setImageResource(R.drawable.down_arrow_32);
		btnDwn.setOnClickListener(new View.OnClickListener() {
			
	//		@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
		btnUp.setImageResource(R.drawable.up_arrow_32);
		btnUp.setOnClickListener(new View.OnClickListener() {
			
	//		@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
        survey.addView(myView);
		
	}
//	private void inflate(string id) {
//	    LinearLayout pyramidLayout = (LinearLayout) findViewById(R.id.pyramid);
//
//
//	    for (int row = 1 ; row <= mSize; ++row) {
//	        View rowView = getLayoutInflater().inflate(R.layout.row, null);
//	        LinearLayout rowLayout = (LinearLayout) rowView.findViewById(R.id.row);
//	        for (int column = 1; column <= row; ++column) {
//	            View btnView = getLayoutInflater().inflate(R.layout.btn, null);
//	            Button btn = (Button) btnView.findViewById(R.id.button);
//	            btn.setId(row*10 + column);
//	            rowLayout.addView(btnView);
//	        }
//	        pyramidLayout.addView(rowView); 
//	    }
//	}
}
